from google.appengine.ext import db
import re

SIMPLIFY_REGEX = re.compile('[^a-zA-Z0-9]+')
def simplify(name):
  """ Simplfies random string to make it easier for lookup
  
  All non-alphanumeric characters converted to underscores
  >>> simplify('123@!#abc')
  '123_abc'
  
  No beginning or trailing underscores
  >>> simplify('_abc!!!')
  'abc'
  
  When dealing with lists, simplify each element
  >>> simplify(['CAT','_ANT','BOY'])
  ['cat', 'ant', 'boy']
  
  Convert keys and models
  >>> class TestModel(db.Model): pass
  >>> simplify(TestModle(key_name='kaboodle'))
  'kaboodle'
  
  """
  if hasattr(name, '__iter__'):
    return [simplify(item) for item in name]
  
  if not name: return ''
  
  if isinstance(name, db.Model): name = item.key()
  if isinstance(name, db.Key): name = item.id_or_name()
  
  return SIMPLIFY_REGEX.sub('', name).strip('_').lower()

